package cn.tedu.myweb.myweb.util;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;

public class HttpClient {
	public static byte[] getData(String url,String Tedurl) throws IOException {
		byte[] data = new byte[0];
			HttpURLConnection conn = (HttpURLConnection)getUrl(url,Tedurl).openConnection();
			//设置超时间为3秒
			conn.setConnectTimeout(1000);
			//防止屏蔽程序抓取而返回403错误
			conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36");
			conn.setRequestProperty("Origin","http://tts.tmooc.cn");
			conn.setRequestProperty("Referer","http://tts.tmooc.cn/video/showVideo?menuId=605103&version=JSD_N_V09");
			conn.setRequestProperty("Host","c.it211.com.cn");
			//得到输入流
			InputStream in = conn.getInputStream();
			byte[] buffer = new byte[1024*4];
			int bytesRead = 0;
			while((bytesRead=in.read(buffer))!=-1) {
				int old = data.length;
				data = Arrays.copyOf(data, data.length+bytesRead);
				for(int i = 0;i<bytesRead;i++) {
					data[old+i] =buffer[i];
				}
			}
			in.close();
		return data;
	}
	public static URL getUrl(String url,String Tedurl) throws MalformedURLException {
		return new URL(Tedurl+url);
	}
	
	public static String byteArrToString(byte[] data) {
		char[] ch = new char[data.length];
		for(int i=0;i<data.length;i++) {
			ch[i] = (char)data[i];
		}
		return String.valueOf(ch);
	}
}
